<template>
  <div id="app">
    <router-view/>
  </div>
</template>
<script>
import { mapState,mapMutations } from 'vuex';
import chatObj from '@/model/chatModel.js';
// let disp = require("@/utils/broadcast");
let me = null;
export default {
  name:'App',
  data(){
    return{
      activatedPage:null,
      ipcRenderer:null
    };
  },
  created(){
    me = this;
    if (this.isElectron){
      this.ipcRenderer = require('electron').ipcRenderer;
      this.ipcRenderer.on('winEvent', (e,event) => {
        switch (event) {
          case 'blur':
            me['chatModule/setWinFocus'](0);
            return;
          case 'focus':
            me['chatModule/setWinFocus'](1);
            return;
          case 'notifyClick':
            console.log("notifyClick");
            me['baseModule/setMainTab']('chat');
            return;
        }
      })
    }
    else{
      me['baseModule/setMainTab']('dashboard');
    }
    this.$EventBus.$on("activatePage",function(obj){
      me.activatedPage = obj;
    });
    if(this.token){
      chatObj.initLocalData(me);
      me.sock_init();
    }
    else{
      me.sock_destroy();
    }
  },
  computed: {
    ...mapState({
      mainTab: ({baseModule}) => baseModule.mainTab,
      userInfo: ({user}) => user.user,
      token: ({user}) => user.token,
      chatWindowsId: ({chatModule}) => chatModule.chatWindowsId,
      winFocus: ({chatModule}) => chatModule.winFocus,
      historyMsgList: ({chatModule}) => chatModule.historyMsgList,
    })
  },
  watch:{
    token(val){
      if(val){
        chatObj.initLocalData(me);
        me.sock_init();
      }
      else{
        clearInterval(me.websockHeartbeatIntervalID);
        me.sock_destroy();
      }
    }
  },
  methods:{
    ...mapMutations(['chatModule/setHistoryMsgList','chatModule/setUnreadMsgCount', 'chatModule/setWinFocus', 'baseModule/setMainTab']),
    sock_init(){
      me.sock_destroy();
      me.websock = new WebSocket(process.env.VUE_APP_API_WSS_URL);
      // console.log(me.websock.readyState);
      me.websock.onmessage = me.sock_onmessage;
      me.websock.onopen = me.sock_onopen;
      me.websock.onerror = me.sock_onerror;
      me.websock.onclose = me.sock_onclose;
    },
    sock_onopen(){
      console.log('socket连接成功');
      clearInterval(me.reConnectIntervalID);
      me.reConnectIntervalID = 0;
      me.login_to_chat();
    },
    sock_onmessage(e){
      var msg = JSON.parse(e.data);
      if(msg.message_type=="pong"){
        console.log("pong");
      }
      else{
        chatObj.onMessage(me, e);
        me.sock_sendHeartbeat();
      }
    },
    sock_onerror(){
      if (me.reConnectIntervalID == 0) {
        me.sock_reconnect();
      }
    },
    sock_onclose(){
      console.log('socket已关闭');
      if(me.token){
        if (me.reConnectIntervalID == 0) {
          me.sock_reconnect();
        }
      }
    },
    sock_reconnect(){
      console.log('socket开始重连……');
      clearInterval(me.websockHeartbeatIntervalID);
      me.websockHeartbeatIntervalID = 0;
      if (me.reConnectIntervalID == 0) {
        me.reConnectIntervalID = setInterval(me.sock_init, 3000);
      }
    },
    sock_sendHeartbeat(){
      me.websock.send(JSON.stringify({type: 'ping',platform:'web'}));
    },
    sock_destroy(){
      if(me.websock){
        me.websock.close();
        me.websock = null;
      }
    },
    login_to_chat(){
      if(me.token){
        me.chat_init();
      }
    },
    chat_init(){
      me.websockHeartbeatIntervalID = setInterval(me.sock_sendHeartbeat, 13000);
      me.websock.send(JSON.stringify({type: 'init'}));
    }
  }
}
</script>
